<template>
  <div class="app-container flex-row">
    <!-- 左侧树 -->
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:290px;">
      <div class="common-title">
        <h2>自定义表单分类</h2>
      </div>
      <category-dict-tree code="05" @selected="handleCategorySelectedInfo" />
    </div>
    <div class="conmmon-container-main flex-main">
      <!--搜索条件-->
      <div class="filter-container">
        <el-form :model="listQuery" :inline="true">
          <el-form-item>
            <el-input v-model="listQuery.categoryName" placeholder="请选择左侧分类节点" disabled />
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.keyword" placeholder="请输入关键字(表单编号或表单名称)" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!--列表-->
      <div class="table-container flex-main">
        <div class="table-container-header">
          <table-toolbar @refresh="handleFilter" @create="handleCreate" @remove="removeRecord" />
        </div>
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          highlight-current-row
          stripe
          height="100%"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="40" />
          <el-table-column :show-overflow-tooltip="true" label="图标" prop="icon" width="70" align="center">
            <template slot-scope="scope">
              <img :src="global.getFileView(scope.row.icon)" class="common-round-image-32" :title="scope.row.name" @error="handleImageError">
            </template>
          </el-table-column>
          <el-table-column label="表单名称" prop="name" min-width="150" sortable align="left">
            <template slot-scope="scope"><span class="color-primary">{{ scope.row.code }}</span>  {{ scope.row.name }}</template>
          </el-table-column>

          <el-table-column label="状态" prop="status" width="80" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status===0" class="color-success">已发布</span>
              <span v-if="scope.row.status===1" class="color-danger">未发布</span>
            </template>
          </el-table-column>
          <el-table-column prop="createdBy" align="center" label="创建人" width="230" :show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.createdBy | optionUserFormat }}<br>{{ scope.row.gmtCreated | formatDate }}</template>
          </el-table-column>
          <el-table-column prop="modifyBy" align="center" label="修改人" width="230" :show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.modifyBy | optionUserFormat }}<br>{{ scope.row.gmtModified | formatDate }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="160">
            <template slot-scope="scope">
              <button-option icon="el-icon-edit-outline" skin="primary" title="设计" @click="handleDesigner(scope.row)" />
              <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
              <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>

    <side-box :show="sideBox.formShow" :title="sideBox.title" @close="sideBox.formShow = !sideBox.formShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="formRules"
          :model="formRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="所属表单分类:">
            <el-input v-model="listQuery.categoryName" :disabled="true" />
          </el-form-item>

          <el-form-item label="图标:" prop="icon">
            <!--<single-image-upload
              ref="logo"
              v-model="formRecord.icon"
              :catalog="constants.FILE_CATALOG_WORK_FLOW_FORM" />-->
            <el-input v-model="formRecord.icon" placeholder="请输入表单图标" show-word-limit maxlength="4" />

          </el-form-item>
          <el-form-item label="名称:" prop="name">
            <el-input v-model="formRecord.name" maxlength="15" show-word-limit placeholder="请输入表单名称" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button :loading="sideBox.buttonLoading" plain type="primary" @click="sideBox.status==='create'?createData():updateData()">保存</el-button>
      </template>
    </side-box>
    <side-box :show="sideBox.designerShow" :title="sideBox.designerTitle" :width="'calc(100% - 20px)'" class="side-modal-box-full" @close="sideBox.designerShow=!sideBox.designerShow">
      <template slot="body">
        <fc-designer ref="formDesigner" />
      </template>
      <template slot="foot">
        <el-button :loading="sideBox.buttonLoading" type="primary" @click="saveFromContentConfirm">保存并发布</el-button>
      </template>
    </side-box>
    <model-dialog
      title="再次确认"
      :visible.sync="dialogVisible"
      width="90%"
      @close="dialogVisible=!dialogVisible">
      <div class="flex-row" style="padding:20px 0">
        <vue-json-editor
          v-model="formContent"
          style="width: 100%;"
          :show-btns="false"
          :mode="'form'"
          lang="zh"
          :expanded-on-start="true" />
      </div>
      <template slot="footer">
        <el-button type="primary" @click="saveFromContent">保存并发布</el-button>
      </template>
    </model-dialog>
  </div>
</template>

<script>
import vueJsonEditor from 'vue-json-editor'
export default {
  components: { vueJsonEditor },
  data() {
    return {
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: '',
        sort: this.common.SORT_DEFAULT
      },
      // 固定写法
      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        formShow: false,
        title: '',
        status: 'create', // 对话框状态
        buttonLoading: false,
        designerShow: false,
        designerTitle: '流程表单在线设计'
      },
      // 固定写法
      formRecord: {},
      formRules: {
        name: [
          { required: true, message: '请输入表单名称', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请输入表单图标', trigger: 'blur' }
        ]
      },
      formDetails: {},
      dialogVisible: false,
      formContent: {}
    }
  },
  created() {
  },
  methods: {
    handleCategorySelectedInfo(data) {
      this.listQuery = {
        ...this.listQuery,
        categoryName: data.name,
        categoryId: data.id
      }
      this.handleFilter()
    },
    // 固定写法开始
    /**
     * 表格全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 表格排序
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    /**
     * 表格行单击
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 固定写法结束
    async fetchData() {
      const response = await this.$store.dispatch('businessFormPage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        sort: this.common.SORT_DEFAULT,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: ''
      }
      this.fetchData()
    },
    // 固定写法结束

    handleCreate() {
      if (!this.listQuery.categoryId) {
        this.msgWarning('请先选择左侧某个节点')
        return
      }
      this.sideBox.status = 'create'
      this.sideBox.formShow = true
      this.sideBox.title = '新增[' + this.listQuery.categoryName + ']类型的表单'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.formRecord = {
          categoryId: this.listQuery.categoryId
        }
      })
    },
    createData() {
      this.formRecord.isNationalStandard = this.selectedTypeIsNationalStandard
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.sideBox.buttonLoading = true
          this.formRecord.dataDictId = this.listQuery.dataDictId
          this.$store.dispatch('businessFormSave', this.formRecord).then(response => {
            this.sideBox.buttonLoading = false
            this.sideBox.formShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.buttonLoading = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.formRecord = Object.assign({}, row)
      this.sideBox.status = 'update'
      this.sideBox.formShow = true
      this.sideBox.title = '编辑[' + this.listQuery.categoryName + '-' + this.formRecord.name + ']'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.formRecord)
          this.sideBox.buttonLoading = true
          this.$store.dispatch('businessFormUpdate', tempData).then(response => {
            this.sideBox.buttonLoading = false
            this.sideBox.formShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.buttonLoading = false
          })
        }
      })
    },
    // 删除数据项
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })

        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('businessFormRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },
    handleDesigner(row) {
      this.$store.dispatch('businessFormGetDetailsById', row.id).then((res) => {
        this.formDetails = res
        this.sideBox.designerTitle = `流程表单在线设计【${row.name}】`
        this.sideBox.designerShow = true
        if (res.formContent) {
          this.$refs.formDesigner.setRule(JSON.parse(res.formContent))
        } else {
          this.$refs.formDesigner.setRule([])
        }
      }).catch((_) => {})
    },
    saveFromContentConfirm() {
      this.formContent = this.$refs.formDesigner.getJson()
      if (JSON.parse(this.formContent).length === 0) {
        this.msgWarning('您还没绘制任何表单内容!')
        return
      }
      this.dialogVisible = true
      this.formContent = JSON.parse(this.$refs.formDesigner.getJson())
    },
    saveFromContent() {
      var formContent = this.$refs.formDesigner.getJson()
      if (JSON.parse(formContent).length === 0) {
        this.msgWarning('您还没绘制任何表单内容!')
        return
      }
      this.$store.dispatch('businessFormSaveContent', { id: this.formDetails.id, formContent: formContent }).then(response => {
        this.sideBox.buttonLoading = false
        this.sideBox.formShow = false
        this.msgSuccess('发布成功')
        this.sideBox.designerShow = false
        this.dialogVisible = false
        this.handleFilter()
      }).catch(() => {
        this.sideBox.buttonLoading = false
      })
    }

  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

</style>
